import { useState, useEffect } from 'react';
import { withRouter } from 'next/router';
import { queryCheckEmpty } from '@/utils';
import Head from '@/components/Head';
import Tkd from '@/ssr/tkd';
// css
import styles from '@/styles/CommonList.module.scss';
// 组件
import Breadcrumb from '@/components/Breadcrumb';
import Pagination from '@/components/Pagination';
import ListItem from '@/pages_components/list/ListItem';
import HotProductPart from '@/pages_components/components/HotProductPart';
import Empty from '@/pages_components/list/Empty';
// ssr api
import { productList_SSR } from '@/ssr';

const pageType = '/ticket';
const Ticket = ({ router, list, total }) => {
    // 筛选条件，初始化
    const _filters = {
        cities: [
            { label: '全部', value: '', chosen: true },
            { label: '林芝', value: '10' },
            { label: '拉萨', value: '11' },
            { label: '阿里', value: '12' }
        ],
        tags: [
            { label: '全部', value: '', chosen: true },
            { label: '官方出票', value: '官方出票' },
            { label: '立即确认', value: '立即确认' },
            { label: '二次确认', value: '二次确认' }
        ]
    }

    const [filters, setFilters] = useState(_filters);
    const { query } = router;
    // 初始化，已筛选条件
    useEffect(() => {
        const params = Object.keys(query);
        if(params.length){
            params.forEach(key => {
                queryHandler(key, query[key])
            })
        }
    }, []);

    // 通过nav切换回本页面第一页，去掉选中筛选
    useEffect(() => {
        if(router.asPath === router.pathname){
            setFilters(_filters);
        }
    }, [router.asPath]);

    // 已筛选条件
    function queryHandler(key, value) {
        switch(key){
            case 'city': {
                choseCity('cities', value, true)
                break
            }
            case 'tag': {
                if(value){
                    value.split(',').forEach(t => {
                        choseTags('tags', t, true)
                    })
                }
                break
            }
        }
    }
    // 统一路由处理
    function routeHandler(key, value) {
        const _query = { ...query };
        _query[key] = value;
        
        const newQuery = queryCheckEmpty(_query);
        router.push({
            pathname: pageType,
            query: {
                ...newQuery
            }
        })
    }
    // 选择目的地
    function choseCity(key, value, init) {
        // 单选
        filters[key].forEach(f => {
            f.chosen = false;
            if (f.value === value) {
                f.chosen = true;
                !init && routeHandler('city', f.value);
            }
        })
        setFilters({...filters})
    }
    // 选择出票方式
    function choseTags(key, value, init) {
        // 多选
        filters[key].forEach(f => {
            if (!value) {
                if (!f.value) {
                    f.chosen = true
                }
                f.chosen = false
            }
            if (!f.value && value) {
                f.chosen = false
            }
            if (f.value === value) {
                f.chosen = !f.chosen
            }
        })
        const tags = filters[key].filter(item => {
            return item.chosen && item.value
        }).map(item => item.value).toString();
        // 若未选择任何标签，默认跳回全部
        if(value && !tags){
            filters[key][0].chosen = true
        }
        setFilters({...filters});
        !init && routeHandler('tag', tags);
    }
    // 筛选条件 Component
    const Filters = (
        <>
            <dl>
                <dt>目的地</dt>
                <dd>
                    {
                        filters['cities'].map(item => {
                            return <span onClick={() => { choseCity('cities', item.value) }} className={item.chosen ? styles['selected'] : ''} key={item.value}>{item.label}</span>
                        })
                    }
                </dd>
            </dl>
            <dl>
                <dt>出票方式</dt>
                <dd>
                    {
                        filters['tags'].map(item => {
                            return <span onClick={() => { choseTags('tags', item.value) }} className={item.chosen ? styles['selected'] : ''} key={item.value}>{item.label}</span>
                        })
                    }
                </dd>
            </dl>
        </>
    )
    return (
        <div className={styles['common-list-page']}>
            {/* 标题/关键字/网页描述 */}
            <Head meta={Tkd[pageType]} />
            {/* 网页内容 */}
            <div className="max-content">
                {/* 面包屑 */}
                <Breadcrumb params={[{ name: '景点门票', url: pageType }]} />
                <div className={styles.cnt}>
                    {/* 左侧 */}
                    <div className={styles['cnt-left']}>
                        {/* 筛选 */}
                         <div className={styles['filter']}>
                            {Filters}
                        </div>
                        {/* 列表 */}
                        <div className={styles['pro-list']}>
                            {
                                !list.length
                                ? <Empty />
                                : list.map(item => <ListItem target={pageType} targetUrl={`${pageType}/${item.id}.html`} data={item} key={item.id} />)
                            }
                        </div>
                        {/* 分页 */}
                        <Pagination root={pageType} total={total} />
                    </div>
                    {/* 右侧，热门列表 */}
                    <div className={styles['cnt-right']}>
                        <HotProductPart product="热门景区" target="/ticket" />
                    </div>
                </div>
            </div>
        </div>
    )
}

// ssr 请求
Ticket.getInitialProps = async (ctx) => {
    const { pathname, query } = ctx;
    const { 
        ssr: list, 
        total
    } = await productList_SSR(pageType, { pathname, query });
    return { list, total }
}

export default withRouter(Ticket)